# -*- coding: utf-8 -*-

import copy
from merge_manager import MergerBase


def get_noneless_doc(input_doc):
    def walk_tree(doc):
        keys = doc.keys()
        for k in keys:
            if doc[k] is None:
                doc.pop(k)
            elif type(doc[k]) == dict:
                walk_tree(doc[k])
            elif type(doc[k]) == list:
                for i in doc[k]:
                    if type(i) == dict:
                        walk_tree(i)
    walk_tree(input_doc)
    return input_doc


class DefaultMerger(MergerBase):
    def __init__(self):
        pass
    def merge(self, task):
        old_doc = task.current_entity_data
        if old_doc is None:
            old_doc = {}
        new_doc = task.new_entity_data
        for key, value in new_doc.iteritems():
            if key[0] == '_': continue       # 以下划线开头的是meta数据, 不进行合并
            if (not value is None):
                old_doc[key] = value

        task.current_entity_data = get_noneless_doc(old_doc)

